package cn.gson.CRM.controller.permission;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.gson.CRM.model.dao.permission.ResourceDao;
import cn.gson.CRM.model.dao.permission.RoleDao;
import cn.gson.CRM.model.entity.Resource;
import cn.gson.CRM.service.permission.ResourceService;

@Controller
@RequestMapping("permission/resource")
public class ResourceController {

	@Autowired
	ResourceDao resourceDao;
	
	@Autowired
	ResourceService resourceService;

	@RequestMapping
	public void index() {

	}

	@RequestMapping({ "form", "form/{id}" })
	public String form(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("r", resourceDao.findOne(id));
		}
		return "permission/resource/form";
	}

	@RequestMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid Resource resource, BindingResult br) {
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			System.out.println(br);
			result.put("err", "校验失败！");
		} else {
			if (resource.getParent().getId() == null) {
				resource.setParent(null);
			}
			resourceDao.save(resource);
			result.put("success", true);
		}
		return result;
	}

	/**
	 * 
	 * @return
	 */
	@RequestMapping({ "/parents", "list" })
	@ResponseBody
	public List<Resource> parents() {
		return resourceService.getTreeData();
	}

	@GetMapping("delete/{id}")
	@ResponseBody
	public String delete(@PathVariable Long id) {
		resourceDao.delete(id);
		return "true";
	}
}
